package com.daidai.apptoservice

import android.app.Application
import android.content.Intent
import dai.android.util.AndroidUtils
import kotlinx.coroutines.*
import kotlin.coroutines.EmptyCoroutineContext

class MyApp : Application() {

    override fun onCreate() {
        super.onCreate()
        MyLog.info("MyApp onCreate called!")

        val processName = AndroidUtils.getCurrentProcessNameByAT()
        if (processName == packageName){
            MyLog.info("准备启动 ServerService....")
            val intent = Intent(this,ServerService::class.java)
            startService(intent)

            startAppEventLoop()

        }else{
            MyLog.info("进程 processName:$processName 启动")
        }
    }

    var tickCount = 0
    private fun startAppEventLoop(){
        CoroutineScope(EmptyCoroutineContext).launch {
            launch(Dispatchers.Default){
                while (isActive){
                    delay(1000L)

                    if (tickCount > 0 && tickCount % 5 == 0){
                        val intent = Intent(applicationContext,ServerService::class.java)
                        intent.putExtra("tick",tickCount)
                        startService(intent)
                    }
                    tickCount++
                }
            }
        }
    }
}